import  { Table, Button, message ,Pagination,PaginationProps,Modal  }  from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import React, { useState,useEffect } from 'react';
import {useNavigate} from 'react-router-dom'
import {GetArticleListApi,DeleteArticleApi} from 'request/api'
import moment from  'moment'

interface DataType {
  key: React.Key;
  title: React.ReactNode;
  time: string;
  action: React.ReactNode;
}

const columns: ColumnsType<DataType> = [
  {
    title: '文章标题',
    dataIndex: 'title',
    width:'60%'
  },
  {
    title: '发布时间',
    dataIndex: 'time',
    width:'20%'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width:"20%"
  },
];

// 操作按钮的组件
const ActionBtn = (props:{id:number;current:number;getListFn:(page:number,pageSize:number)=>void}) => {
  const navigate = useNavigate()
  const [visible, setVisible] = useState(false);
  let editable = localStorage.getItem('editable')
  const showModal = () => {
    console.log(editable)
    if(editable==='0'){
      console.log(11)
        message.error("暂无权限删除文章")
    }
    setVisible(true);
  };
  const handleOk = (e: React.MouseEvent<HTMLElement>) => {
    deleteFn()
    setVisible(false);
  };

  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    setVisible(false);
  };
  const goToEdit = (id:number) =>{
    navigate('/edit/'+id)
  }
  const deleteFn = ()=>{
    
    DeleteArticleApi({id:props.id}).then((res:any) => {
      if(res.errCode === 0){
        message.success(res.message)
        props.getListFn(props.current,10)
      }else{
        message.error(res.message)
      }
    })
  }

  
  return(
    <>
        <Button type='primary' onClick={()=>goToEdit(props.id)} style={{marginRight:'20px'}}>编辑</Button>
        <Button type='primary' onClick={showModal} danger>删除</Button>
        <Modal
        title="提示"
        visible={visible}
        cancelText='取消'
        okText='确定'
        onOk={handleOk}
        onCancel={handleCancel}
        okButtonProps={{ disabled: editable==='0' }}
        // cancelButtonProps={{ disabled: true }}
      >
        <p>{editable==='0'?'暂无权限删除文章':'你确定删除吗？'}</p>
      </Modal>
    </>
  )
}

// 标题于副标题组件
const TitleComp = (props:{title:string;subTitle?:string}) => (
  <>
    <div><a href="!#">{props.title}</a></div>
    <p style={{color:'#999'}}>{props.subTitle || ''}</p>
  </>
)



const List: React.FC = () => {

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  
  const [data, setData] = useState<DataType[]>([])
  // 分页总数据
  const [total,setTotal] = useState(0)
  const [current,setCurrent] = useState(1)

  const getListFn = (page:number,pageSize:number)=>{
    GetArticleListApi({
      current:page,
      counts:pageSize
    }).then((res:any)=>{
      if(res.errCode === 0){
        message.success(res.message)
      }
      let newarr:DataType[] = []

      interface IItem {
        title:string;
        subTitle:string;
        date:string;
        id:number;
      }
      setTotal(res.data.total)
      res.data.arr.map((item:IItem)=>{
        let obj = {
          key:item.id,
          title : <TitleComp title={item.title} subTitle={item.subTitle}/>,
          time:moment(item.date).format('YYYY-MM-DD hh:mm:ss'),
          action:<ActionBtn current= {current} getListFn={getListFn} id={item.id}/>
        }
        newarr.push(obj)
      })
      setData(newarr)
    })
  }

  useEffect(()=>{
    getListFn(1,10)
    
  },[])

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: changableRowKeys => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: changableRowKeys => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  const onPageChange: PaginationProps['onShowSizeChange'] = (current:number, pageSize:number) => {
    setCurrent(current)
    getListFn(current,pageSize)
    console.log(current, pageSize);
  };

  return (
    <>
    <Table showHeader={false} columns={columns} dataSource={data} pagination={false} style={{marginBottom:'20px',height:'800px',overflowY: 'scroll'}}/>
    <Pagination 
      defaultCurrent={1}
      total={total}
      onChange={onPageChange}
      showSizeChanger={false}
      style={{float:'right',margin:'10px 20px 0 0'}}
    />
    </>
  );
};


export default List;